<script setup>
    import { ref, reactive, onMounted, computed, watch } from 'vue';
    import axios from 'axios';
    import { ElMessage, ElLoading } from 'element-plus'

    const dataLocal = {
        route: "/wp-admin/admin-ajax.php",
        nonce: "asdf",
        data: {
            user: [
                { id: 1, name: "111" },
                { id: 2, name: "222" },
            ],
        },
    };

    const dataServer = dataLocal.data;

    //addMenu菜单弹窗控制
    const addMenu = ref(false);
    const forms = reactive({
        siteName: '',
        siteUrl: ''
    })

    //网站列表存储
    const siteList = ref([]);
    //当前网站参数
    const currentSite = reactive({
        title: '',
        Infotitle: '',
        time: '',
        description: '',
        content: '',
        url: ''
    })
    //当前网站ID
    const currentSiteId = ref('');
    //储存网站标题和URL
    const addMenus = () => {
        addMenu.value = true;
        forms.siteName = '';
        forms.siteUrl = '';
    }
    const handleClose = () => {
        addMenu.value = false;
    }
    const handleCloseData = () => {
        addDatato.value = false;
    }
    //判断是否是URL
    const isUrl = (str) => {
        // URL的正则表达式模式
        const pattern = /^(https?:\/\/)?(www\.)?[a-zA-Z0-9]+\.[a-z]{2,}(\/.*)?$/;
        return pattern.test(str);
    }
    //添加MENU方法
    const addMenuFun = () => {
        if (forms.siteName == '' || forms.siteUrl == '') {
            ElMessage('请填写完整信息！');
            return;
        }
        if (!isUrl(forms.siteUrl)) {
            ElMessage('请填写正确的URL!');
            return;
        }
        let formData = new FormData();
        formData.set('action', 'addMenu_list');
        formData.set('data', JSON.stringify(forms));
        axios.post(dataLocal.route, formData, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data'
            },
        }).then(res => {
            console.log(res.data);
            if (res.data.code == 1) {
                ElMessage('添加成功！');
                const dataes = {
                    'ID': res.data.rid,
                    'post_title': forms.siteName,
                }
                siteList.value.unshift(dataes)
                return
            }
        })
        addMenu.value = false;
    }
    const get_artlists = () => {
        let formData = new FormData();
        formData.set('action', 'get_artlists');
        axios.post(dataLocal.route, formData, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data'
            },
        }).then(res => {
            console.log(res.data);
            if (res.data.code == 1) {
                siteList.value = res.data.data;
                console.log(siteList.value);
            }
        })
    }
    const getAttr = (id) => {
        currentSiteId.value = id;
        let formData = new FormData();
        formData.set('action', 'get_art_list');
        formData.set('id', currentSiteId.value);
        axios.post(dataLocal.route, formData, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data'
            },
        }).then(res => {
            currentSite.url = res.data.data.url;
            currentSite.title = res.data.data.title;
            currentSite.description = res.data.data.description;
            currentSite.content = res.data.data.content;
            currentSite.time = res.data.data.time;
            currentSite.Infotitle = res.data.data.Infotitle;
        })
    }
    //防抖函数
    const debounce = (fn, delay = 300) => {
        let timer = null;
        return function (...args) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                fn.call(this, ...args)
            }, delay);
        }
    }
    const addAttrlist = () => {
        let formData = new FormData();
        formData.set('action', 'get_artlistses');
        formData.set('id', currentSiteId.value);
        formData.set('data', JSON.stringify(currentSite));
        axios.post(dataLocal.route, formData, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data'
            },
        }).then(res => {
            console.log(res.data);
            if (res.data.code == 1) {
                ElMessage('更新成功！');
                return
            }
        })
    }
    //储存采集到的数据
    const saveData = ref([]);
    const progress = ref(0);
    const caijiFun = () => {
        if (currentSite.title == '' || currentSite.content == '' || currentSite.Infotitle == '') {
            ElMessage('请填写完整！');
            return
        }
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        let formData = new FormData();
        formData.set('action', 'caijiFun');
        formData.set('data', JSON.stringify(currentSite));
        axios.post(dataLocal.route, formData, {
            onUploadProgress: (progressEvent) => {
                progress.value = (progressEvent.loaded / progressEvent.total) * 100;
            }
        }, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data'
            },
        }).then(res => {
            console.log(res);
            saveData.value = res.data;
            loading.close();
            ElMessage('采集成功！');
        })
    }

    const addDatato = ref(false);
    

    //获取网站栏目
    const categoryList = ref([]);
    const sendDatasTo = () => {
        if (saveData.value.length == 0) {
            ElMessage('请先采集数据！');
            return
        }
        addDatato.value = true;
        let formData = new FormData();
        formData.set('action', 'get_cate_by_RestAPI');
        axios.post(dataLocal.route, formData, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data'
            },
        }).then(res => {
            console.log(res);
            categoryList.value = res.data;
            console.log(categoryList.value);
        })
    }
    

    //选择分类存到数据库
    const  addMuneTotypes = () =>{
        let formDatas = new FormData();
        formDatas.set('action', 'add_cate_by_RestAPI');
        formDatas.set('cateData', JSON.stringify(value1.value));
        formDatas.set('cate_id', currentSiteId.value);
        axios.post(dataLocal.route, formDatas,{
            headers:{
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data charset=UTF-8'
            }
        }).then(res => {
            console.log('分类入库成功！');
        })
    }

    //添加即使任务
    const addTask = () => {
        let formData = new FormData();
        formData.set('action', 'add_task_by_RestAPI');
        formData.set('taskData', JSON.stringify(value1.value));
        axios.post(dataLocal.route, formData, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data'
            }
        }).then(res => {
            console.log(res);
        })
    }
    //发布文章到数据库
    const addDatatoes = () => {
        if(value1.value.length == 0){
            ElMessage('请先选择分类！');
            return
        }
        let formData = new FormData();
        formData.set('cateData', JSON.stringify(saveData.value));
        formData.set('action', 'set_in_cate_by_RestAPI');
        formData.set('cateIdList', JSON.stringify(value1.value));
        addMuneTotypes();
        axios.post(dataLocal.route, formData, {
            headers: {
                "X-WP-Nonce": dataLocal.nonce,
                'Content-Type': 'application/form-data charset=UTF-8'
            },
        }).then(res => {
            if(res.data.code == 1){
                ElMessage('发布成功！');
                addDatato.value = false;
            }
            // ElMessage('发布成功！');
            // addDatato.value = false;
        })
    }
    const value1 = ref([]);

    // //储存计划任务名称
    // const checked1 = ref(false);
    // //任务名称
    // const name1 = ref('');
    // const renwuData = reactive({
    //     name1:'',
    //     time:''
    // })
    // //关闭窗口
    // const handleCloseRenwu = () => {
    //     checked1.value = false;
    // }

    // const checked1Fun = () => {
    //     //监控是否选择了栏目
    //     if(value1.value.length == 0){
    //         ElMessage('请先选择栏目！');
    //         checked1.value = false;
    //         return
    //     }
    //     if(renwuData.name1 == ''){
    //         ElMessage('请输入任务名称');
    //         checked1.value = false;
    //         return
    //     }
    //     if(renwuData.time == ''){
    //         ElMessage('请输入任务执行时间');
    //         checked1.value = false;
    //         return
    //     }
    // }
    //页面初始加载
    onMounted(() => {
        //获取选项值
        get_artlists();
    });
</script>

<template>
    <div class="cont">
        <div class="con contLeft">
            <h1>采集规则配置</h1>
            <div class="forms">
                <div class="butlist">
                    <el-button class="ceshi" type="success" v-for="item in siteList"
                        @click="debounce(getAttr(item.ID), 5000)" :class="currentSiteId == item.ID ? 'cur' : ''">{{
                        item.post_title }}</el-button>
                    <el-button type="danger" @click="addMenus">add+</el-button>
                </div>
                <el-dialog v-model="addMenu" title="Add Menus" width="30%" :before-close="handleClose">
                    <span class="mennuModel">
                        <label>
                            siteName:<el-input v-model="forms.siteName" placeholder="Please enter siteName" />
                        </label>
                        <label>
                            siteUrl:<el-input v-model="forms.siteUrl" placeholder="Please enter siteUrl" />
                        </label>
                    </span>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="addMenu = false">Cancel</el-button>
                            <el-button type="primary" @click="addMenuFun">Confirm</el-button>
                        </span>
                    </template>
                </el-dialog>

                <div class="guize" v-if="currentSiteId != ''">
                    <h3>填写规则</h3>
                    <div class="guizebox">
                        <h5>列表页规则</h5>
                        <label for="title">
                            <span>URL</span>
                            <input type="url" v-model="currentSite.url" name="url" class="url" id="url"
                                placeholder="请填写URL">
                        </label>
                        <label for="title">
                            <span style="color: rgb(0, 255, 149);">标题</span>
                            <input type="text" v-model="currentSite.title" name="title" class="title" id="title"
                                placeholder="请填写标题标签">
                        </label>
                        <h5>详情页规则</h5>
                        <label for="title">
                            <span style="color: rgb(0, 255, 149);">标题</span>
                            <input type="text" v-model="currentSite.Infotitle" name="title" class="title" id="title"
                                placeholder="请填写标题标签">
                        </label>
                        <label for="description">
                            <span>描述</span>
                            <input type="text" v-model="currentSite.description" name="description" class="description"
                                id="description" placeholder="请填写描述标签">
                        </label>
                        <label for="title">
                            <span>时间</span>
                            <input type="text" v-model="currentSite.time" name="time" class="time" id="time"
                                placeholder="请填写时间标签">
                        </label>
                        <label for="content">
                            <span style="color: rgb(0, 255, 149);">内容</span>
                            <input type="text" v-model="currentSite.content" name="content" class="content" id="content"
                                placeholder="请填写内容标签">
                        </label>
                    </div>

                    <!-- 发布内容到网站 已弹窗的形式-->
                    <el-dialog v-model="addDatato" title="发送数据" width="30%" :before-close="handleCloseData">
                        <div class="mennuModel">
                            <div class="selectes">
                                <span>选择栏目： </span>
                                <el-select v-model="value1" multiple  placeholder="Select" style="width: 240px">
                                    <el-option v-for="item in categoryList" :key="item.term_id" :label="item.name"
                                        :value="item.term_id" />
                                </el-select>
                            </div>
                            <!-- <el-checkbox label="是否开启定时任务" v-model="checked1" size="small"/>
                            <el-dialog v-model="checked1" title="添加任务名称" width="30%" :before-close="handleCloseRenwu">
                                <span class="mennuModel">
                                    <label>
                                        任务名称:<el-input v-model="renwuData.name1" placeholder="请输入任务名称" /><br>
                                        任务名称:<el-radio-group v-model="renwuData.time" class="ml-4">
                                            <el-radio label="12:00" size="large">每天12:00</el-radio>
                                            <el-radio label="9:00" size="large">每天9:00</el-radio>
                                          </el-radio-group>
                                    </label>
                                </span>
                                <template #footer>
                                    <span class="dialog-footer">
                                        <el-button @click="checked1 = false">Cancel</el-button>
                                        <el-button type="primary" @click="checked1Fun">Confirm</el-button>
                                    </span>
                                </template>
                            </el-dialog> -->
                        </div>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="addDatato = false">取消</el-button>
                                <el-button type="primary" @click="addDatatoes()">提交</el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <!-- 发布内容到网站 已弹窗的形式-->

                    <div class="anniu">
                        <el-button type="danger" @click="addAttrlist">确认更新</el-button>
                        <el-button type="danger" @click="caijiFun">确认采集</el-button>
                        <el-button type="success" @click="sendDatasTo">发布内容</el-button>
                    </div>
                </div>
                <!-- <div class="routers">
                    <router-link to="/">路由1</router-link>
                    <router-link to="/luyouyi">路由2</router-link>
                    <router-view></router-view>
                </div> -->
            </div>
        </div>
        <div class="con contRight">
            <h1>数据入库</h1>
            <div class="forms datalist">
                <el-table :data="saveData" style="width: 100%" height="800" row-key="id" border lazy :load="load"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                    <el-table-column prop="title" label="title" />
                    <el-table-column prop="content" label="content" />
                </el-table>
            </div>
        </div>
    </div>
</template>


<style scoped>
    .cont {
        width: 100%;
        height: 100%;
        background: #fff;
        display: flex;
        flex-direction: row;
        padding: 0;
        margin: 0;
        font-family: 'Courier New', Courier, monospace;
    }

    .con {
        flex: 1;
        margin-right: 8px;
    }

    .con h1 {
        background-color: aliceblue;
        height: 40px;
        line-height: 40px;
        padding-left: 10px;
        font-size: 16px;
        position: relative;
    }

    .contLeft h1::before {
        content: '';
        width: 120px;
        height: 3px;
        background-color: red;
        position: absolute;
        left: 0;
        top: 38px;
    }

    .contRight h1::before {
        content: '';
        width: 120px;
        height: 3px;
        background-color: red;
        position: absolute;
        left: 0;
        top: 38px;
    }

    .forms {
        padding: 20px 10px;
    }

    .el-button--success,
    .el-button--danger {
        margin: 0 10px 10px 0;
    }

    .mennuModel .el-input {
        margin-bottom: 10px;
    }

    .mennuModel label {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        flex-direction: column;
    }

    .el-input__wrapper {
        padding: 0;
    }

    .guize {
        margin: 15px 0;
    }

    .guize h3 {
        color: red;
        border-bottom: 2px solid #d2d2d2;
        padding: 15px 0;
        box-sizing: border-box;
        font-size: 16px;
    }

    .guizebox {
        padding: 15px 0;
    }

    .guizebox label {
        margin-bottom: 15px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    input,
    select {
        height: 35px;
        line-height: 35px;
        border: 1px solid #d2d2d2;
    }

    .guizebox label span {
        margin-right: 10px;
        font-size: 14px;
    }

    .guizebox label input {
        flex: 1;
        padding-left: 15px;
    }

    .cur {
        background-color: aqua;
        color: red;
    }

    .guizebox h5 {
        margin-bottom: 15px;
        color: red;
    }

    .datalist {
        max-height: 1000px;
        overflow-y: scroll;
        padding: 30px 0;
    }

    .selectes {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
    }

    .selectes span {
        font-size: 12px;
    }
</style>